package main

import (
	"errors"
	"strings"
)

import (
	"tksUint"
)

type OperateCallback func([]string) interface{}

var opetates map[string]OperateCallback

func init() {
	opetates = make(map[string]OperateCallback)
}

func getCmd(data string) (string, []string) {
	all := strings.Split(strings.Trim(data, "\r\n"), " ")
	if len(all) > 0 {
		return all[0], all[1:len(all)]
	}
	return "", nil
}

func Register(cmd string, cb OperateCallback) {
	opetates[cmd] = cb
}

func Process(data string) (string, error) {
	cmd, params := getCmd(data)
	cb, ok := opetates[cmd]
	if ok {
		s := cb(params)
		result, err := tksUint.MsgToBuf(s)
		if err == nil {
			return string(result), nil
		} else {
			return "", err
		}
	} else {
		return "", errors.New("the cmd is not exists!!!")
	}
}
